import { Space, Notification } from "@douyinfe/semi-ui";
import swr from "../utils/swr";
import Page from "../utils/page";
import { Table, Text, Loading, Card, Grid, Button } from "@nextui-org/react";
import { IconEdit, IconDelete } from "@douyinfe/semi-icons";
import DeleteConfirmation from "../utils/delete-confirmation";
import { useState } from "react";
import { BASEURL } from "../utils/config";
import { mutate } from "swr";
import EditStudent from "../utils/edit-student";
import NewStudent from "../utils/new-student";

export default function Home() {
  const [editDialogVisiable, setEditDialogVisiable] = useState(false);
  const [editDialogData, setEditDialogData] = useState({});
  const [deleteDialogVisiable, setDeleteDialogVisiable] = useState(false);
  const [deleteDialogData, setDeleteDialogData] = useState({});
  const [newDialogVisiable, setNewDialogVisiable] = useState(false);
  const [newDialogData, setNewDialogData] = useState({});
  const { data, isLoading, isError } = swr(`/students`);
  if (
    isLoading ||
    typeof data === "undefined" ||
    typeof data.detail !== "undefined"
  ) {
    return (
      <Page page="/students">
        <Loading />
      </Page>
    );
  } else if (isError) {
    return (
      <Page page="/students">
        <Text>获取学生信息失败</Text>
      </Page>
    );
  }
  const columns = [
    {
      label: "届次",
      key: "year",
    },
    {
      label: "班级",
      key: "class",
    },
    {
      label: "学生姓名",
      key: "name",
    },
    {
      label: "性别",
      key: "sex",
    },
    {
      label: "身份证号",
      key: "id_number",
    },
    {
      label: "手机号",
      key: "phone_number",
    },
    {
      label: "操作",
      key: "operates",
    },
  ];
  const table = {};
  let classes = 0;
  let key = 1;
  for (let year in data) {
    if (typeof data[year] === "undefined") {
      continue;
    }
    for (let class_name in data[year]) {
      if (JSON.stringify(data[year][class_name]) == "{}") {
        // 过滤空班级
        continue;
      }
      classes++;
      for (let student_name in data[year][class_name]) {
        if (typeof table[student_name] === "undefined") {
          table[student_name] = {
            key: key++,
            year: year,
            class: class_name,
            sex: data[year][class_name][student_name].sex,
            id_number: data[year][class_name][student_name].id_number,
            phone_number: data[year][class_name][student_name].phone_number,
          };
        }
      }
    }
  }
  const rows = [];
  for (let student_name in table) {
    rows.push({
      name: student_name,
      ...table[student_name],
      operates: (
        <Space>
          <IconEdit
            size="large"
            onClick={() => {
              setEditDialogVisiable(true);
              setEditDialogData({
                year: table[student_name].year,
                class: table[student_name].class,
                name: student_name,
                sex: table[student_name].sex,
                id_number: table[student_name].id_number,
                phone_number: table[student_name].phone_number,
              });
            }}
          />
          <IconDelete
            size="large"
            onClick={() => {
              setDeleteDialogVisiable(true);
              setDeleteDialogData({
                year: table[student_name].year,
                class: table[student_name].class,
                name: student_name,
              });
            }}
          />
        </Space>
      ),
    });
  }

  return (
    <Page page="/students">
      <div
        style={{
          margin: "1rem",
        }}
      >
        <Card css={{ marginBottom: 15 }}>
          <Grid.Container gap={2} alignItems="baseline">
            <Grid xs={4}>
              <Text>学生总人数：{key - 1}</Text>
            </Grid>
            <Grid xs={4}>
              <Text>总班级数：{classes}</Text>
            </Grid>
            <Grid xs={4}>
              <Button
                auto
                onClick={() => {
                  setNewDialogVisiable(true);
                  setNewDialogData({
                    year: 2021,
                    class: "班级名称",
                    name: "学生姓名",
                  });
                }}
              >
                添加学生
              </Button>
            </Grid>
          </Grid.Container>
        </Card>
        <Table
          aria-label="考试列表"
          css={{
            height: "auto",
            minWidth: "100%",
          }}
        >
          <Table.Header columns={columns}>
            {(column) => (
              <Table.Column key={column.key}>{column.label}</Table.Column>
            )}
          </Table.Header>
          <Table.Body items={rows}>
            {(item) => (
              <Table.Row key={item.key}>
                {(columnKey) => <Table.Cell>{item[columnKey]}</Table.Cell>}
              </Table.Row>
            )}
          </Table.Body>
        </Table>
        <NewStudent
          newDialogVisiable={newDialogVisiable}
          setNewDialogVisiable={setNewDialogVisiable}
          newDialogData={newDialogData}
          setNewDialogData={setNewDialogData}
        />
        <EditStudent
          editDialogVisiable={editDialogVisiable}
          setEditDialogVisiable={setEditDialogVisiable}
          editDialogData={editDialogData}
          setEditDialogData={setEditDialogData}
        />
        <DeleteConfirmation
          deleteDialogVisiable={deleteDialogVisiable}
          setDeleteDialogVisiable={setDeleteDialogVisiable}
          callback={() => {
            fetch(
              `${BASEURL}/students/${deleteDialogData.year}/${deleteDialogData.class}/${deleteDialogData.name}`,
              {
                method: "DELETE",
                headers: {
                  Authorization: `Bearer ${localStorage.getItem("token")}`,
                },
              }
            )
              .then((res) => {
                return res.status === 204 ? Promise.resolve({}) : res.json();
              })
              .then((res) => {
                if (typeof res.detail === "undefined") {
                  Notification.success({
                    content: `删除成功`,
                  });
                } else {
                  Notification.error({
                    content: `删除失败 ${res.detail.msg}`,
                  });
                }
                mutate(`${BASEURL}/students`);
              })
              .catch((err) => {
                Notification.error({
                  content: `删除失败 ${err}`,
                });
              });
            setDeleteDialogVisiable(false);
          }}
        >
          <Text size={18}>
            正在删除 {deleteDialogData.year} 届的 {deleteDialogData.name}
          </Text>
        </DeleteConfirmation>
      </div>
    </Page>
  );
}
